package cn.huaqingcheng.tianshu.application.http;

import cn.huaqingcheng.tianshu.common.core.Base64Tool;
import cn.huaqingcheng.tianshu.core.sys.param.SysFileUploadParam;
import cn.huaqingcheng.tianshu.core.sys.param.SysFileUploadResponse;
import cn.huaqingcheng.tianshu.core.sys.service.SysFileService;
import cn.huaqingcheng.tianshu.security.annotation.CurrentAccountId;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;

/**
 * 文件
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
public class FileController {

    private final SysFileService fileService;


    /**
     * 文件上传
     */
    @PostMapping(value = "/upload", headers = "content-type=application/octet-stream")
    public SysFileUploadResponse upload(
            InputStream is,
            @CurrentAccountId Long accountId,
            @RequestParam("originalName") String originalName,
            @RequestParam(value = "groupId", defaultValue = "-1") Long groupId
    ) {
        SysFileUploadParam param = new SysFileUploadParam()
                .setAccountId(accountId)
                .setGroupId(groupId)
                .setOriginalName(originalName);
        return fileService.upload(is, param);
    }

    /**
     * 读取文件
     */
    @GetMapping
    public ResponseEntity<?> read(
            @RequestParam("uri") URI uri,
            @RequestParam(value = "redirect", defaultValue = "true") Boolean redirect
    ) {
        return fileService.read(uri, redirect);
    }

    /**
     * 读取文件 同时也是资源引用翻译
     * @param codingUri base64编码后的文件引用
     */
    @GetMapping("/{codingUri}")
    public ResponseEntity<?> read(
            @PathVariable("codingUri") String codingUri,
            @RequestParam(value = "redirect", defaultValue = "true") Boolean redirect
    ) {
        String str = Base64Tool.decode(codingUri);
        return fileService.read(URI.create(str), redirect);
    }

}
